<?php

namespace app\api\controller;
use app\api\controller\Common;
use think\Db;

class Im extends Common {
    //获取聊天记录
    public function getMessageList() {
	    $tokenRes = $this->checkToken(1);
	    if ($tokenRes['status'] == 400) {
		    datamsg(400, $tokenRes['mess'], $tokenRes['data']);
	    }else{
            $userId =  $tokenRes['user_id'];
        }
        $page = input('post.page', 1);
        if (!preg_match("/^\\+?[1-9][0-9]*$/", $page)) {
            datamsg(400, 'page参数错误');
        }
        $shopToken = input('post.shop_token');

        $pageSize = 10;
        $offset = ($page - 1) * $pageSize;
        $chatToken = Db::name('member_token')->where('user_id', $userId)->value('token');

        $chatLog = Db::name('chat_message')->where("((fromid='{$shopToken}' and toid='{$chatToken}') or (fromid='{$chatToken}' and toid='{$shopToken}'))")
            ->order('createtime desc')
            ->limit($offset,$pageSize)
            ->select();

        foreach ($chatLog as $k => $v){
            $memberId = Db::name('member_token')->where('token',$v['fromid'])->value('user_id');
            $chatLog[$k]['from_user'] = Db::name('member')->where('id',$memberId)->find();
            $chatLog[$k]['from_user']['avatar'] = url_format($chatLog[$k]['from_user']['headimgurl'],$this->webconfig['weburl']);
        }

        datamsg(200, 'success', $chatLog);

    }


}
